package com.bckj.fastboot.core.extra.i18n;

import com.bckj.fastboot.core.lang.enums.EnumMessage;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

/**
 * 获取i18n资源文件
 */
@Component
public class MessageUtils implements ApplicationContextAware {

    private static volatile MessageSource messageSource;

    /**
     * 根据消息键和参数 获取消息
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args) {
        return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
    }

    public static String message(EnumMessage<?> em, Object... args) {
        if (em.getMessageCode() == null || em.getMessageCode().isEmpty()) {
            return em.getMessage();
        }
        return message(em.getMessageCode(), args);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (applicationContext.containsBean("fastMessageSource")) {
            messageSource = (MessageSource) applicationContext.getBean("fastMessageSource");
        } else {
            messageSource = (MessageSource) applicationContext.getBean("messageSource");
        }
    }
}